import IpcParams from "@/ipc/IpcParams";
import DexieCtx from "@/utils/dexiectx";

export default class MajorRunner {
  constructor(interval) {
    const minutes = 60
    this.interval = interval ?? (minutes * 60 * 1000 + 5000)
  }

  // run all accounts
  async start() {
    this.run()
    const self = this
    this.timer = setInterval(() => {
      self.run()
    }, this.interval);
  }

  stop() {
    clearInterval(this.timer)
  }

  async run() {
    const dexie = await DexieCtx.db()
    let results = await dexie.major.toArray()
    results = results.filter(item => (item.tgweb ?? "") != "")
    const project = await dexie.projects.get({
      name: "major"
    })
    // 用户没设置邀请url，则使用我们自己的邀请url
    let inviteList = project.inviteList ?? []
    // 一次10个并行
    let index = 0
    let step = 10
    while (index < results.length) {
      try {
        let promises = []
        for (let i = index; i < index + step; i++) {
          if (i >= results.length) {
            break;
          }
          const element = results[i]
          if (inviteList.length > 0) {
            const inviteUrl = inviteList[i % inviteList.length]
            element.inviteUrl = inviteUrl
          }
          const associatAccount = await dexie.accounts.get({
            phone: element.phone
          })
          element.proxy = associatAccount.proxy
          const prms = window.gameAPI.invoke(new IpcParams("runMajor", element))
          promises.push(prms)
        }
        try {
          const promiseResults = await Promise.allSettled(promises)
          for (let index = 0; index < promiseResults.length; index++) {
            const ipcResult = promiseResults[index].value;
            if (ipcResult.error != null) {
              console.error(ipcResult.error)
            }
            const gameResult = ipcResult.params
            await dexie.major.where('phone').equals(gameResult.phone).modify(gameResult)
          }
        } catch (error) {
          console.error(error)
        }
        console.log(Date() + "major game finished " + index + "~" + (index + step))
        index += step
      } catch (error) {
        console.error(error)
        continue
      }
    }
  }
}